package cn.easier.activity.console.service.impl;

import cn.easier.activity.console.params.MessagePostParams;
import cn.easier.activity.console.service.MessagePostQueueService;
import cn.easier.activity.console.service.MessagePostService;
import cn.easier.activity.console.utils.DelayMessage;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessagePostQueueServiceImpl implements MessagePostQueueService {

    private Logger logger = LoggerFactory.getLogger(MessagePostQueueServiceImpl.class);

    @Value("${metadata.activity-platform.message-post.serialize-path}")
    public String serializePath;

    @Value("${metadata.configuration.static-resource-path}")
    public String realPath;

    private final MessagePostService messagePostService;

    @Autowired
    public MessagePostQueueServiceImpl(MessagePostService messagePostService) {
        this.messagePostService = messagePostService;
    }

    @Async
    @Override
    public void queue() {
        try {
            logger.info("从本地恢复未完成任务: 开始");
            File file = new File(realPath + serializePath + SERIALIZE_FILE_NAME);
            try {
                if (file.exists()) {
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    List<String> list = reader.lines().collect(Collectors.toList());
                    reader.close();
                    for (String line : list) {
                        if (StringUtils.isNotBlank(line)) {
                            try {
                                DelayMessage delayMessage = JSON.parseObject(line, DelayMessage.class);
                                offer(delayMessage);
                            } catch (Exception e) {
                                logger.warn("从本地恢复未完成任务: 解析失败: [{}]", line);
                            }
                        }
                    }
                    logger.info("从本地恢复未完成任务: 新增任务{}条", list.size());
                } else {
                    new File(realPath + serializePath).mkdirs();
                    file.createNewFile();
                    logger.info("从本地恢复未完成任务: 文件不存在，已新建");
                }
            } catch (Exception e) {
                logger.error("邮短投递队列读取本地历史信息发生异常:{}", e.getMessage());
                e.printStackTrace();
            }
            while (true) {
                DelayMessage message = DELAY_QUEUE.take();
                MessagePostParams params = message.getParams();
                messagePostService.send(params);
                updateFile();
            }
        } catch (InterruptedException e) {
            logger.error("邮短投递队列发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public boolean offer(DelayMessage delayMessage) {
        MessagePostParams params = delayMessage.getParams();
        messagePostService.preSend(params);
        boolean offer = DELAY_QUEUE.offer(delayMessage);
        updateFile();
        return offer;
    }

    /**
     * 更新本地缓存文件
     */
    private synchronized void updateFile() {
        try {
            File file = new File(realPath + serializePath + SERIALIZE_FILE_NAME);
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            ArrayList<DelayMessage> list = new ArrayList<>(DELAY_QUEUE);
            for (DelayMessage delayMessage : list) {
                writer.write(JSON.toJSONString(delayMessage));
                writer.newLine();
            }
            writer.close();
        } catch (IOException e) {
            logger.error("邮短投递队列保存本地信息发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
